import React, { useState, useEffect } from 'react';
import { View, Text, Dimensions, FlatList, StyleSheet } from 'react-native';
import { calculatePages } from '../utils/pageUtils';

interface ReaderViewProps {
  content: string;
  fontSize: number;
  backgroundColor: string;
}

export const ReaderView: React.FC<ReaderViewProps> = ({
  content,
  fontSize,
  backgroundColor,
}) => {
  const [pages, setPages] = useState<string[]>([]);
  const [currentPage, setCurrentPage] = useState(0);
  
  useEffect(() => {
    const { width, height } = Dimensions.get('window');
    const calculatedPages = calculatePages(content, fontSize, width, height);
    setPages(calculatedPages);
  }, [content, fontSize]);

  return (
    <View style={[styles.container, { backgroundColor }]}>
      <FlatList
        data={pages}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        renderItem={({ item }) => (
          <View style={styles.page}>
            <Text style={[styles.text, { fontSize }]}>{item}</Text>
          </View>
        )}
        onMomentumScrollEnd={(e) => {
          const offset = e.nativeEvent.contentOffset.x;
          const page = Math.round(offset / Dimensions.get('window').width);
          setCurrentPage(page);
        }}
      />
      <Text style={styles.pageInfo}>{`${currentPage + 1}/${pages.length}`}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  page: {
    width: Dimensions.get('window').width,
    padding: 20,
  },
  text: {
    lineHeight: 24,
  },
  pageInfo: {
    position: 'absolute',
    bottom: 20,
    right: 20,
  },
});
